package jim.h.commons;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptTest {

    public static void main(String[] args) throws ScriptException, NoSuchMethodException, IOException {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        System.out.println(engine.getFactory().getNames());
        System.out.println(engine.getFactory().getParameter("THREADING"));

        String script = getScript();

        long start = System.currentTimeMillis();
        engine.eval(script);
        for (int i = 0; i < 10000; i++) {
            runByEngine(engine);
        }
        System.out.println(System.currentTimeMillis() - start);
        
        HotSwapTest.print("hello HotSwap");
    }

    private static Object runByEngine(ScriptEngine engine) throws ScriptException, NoSuchMethodException {
        Invocable inv = (Invocable) engine;
        Object result = inv.invokeFunction("MadeLine", "2011-08-06 17:10:25", "富阳市", "到达处理中心,来自富阳市", "FFFFFF",
                                           "trackListEven", 3);
        return result;
    }

    private static String getScript() throws IOException {
        InputStream is = ScriptTest.class.getClassLoader().getResource("f.js").openStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer buf = new StringBuffer();
        String str = null;
        while ((str = reader.readLine()) != null) {
            buf.append(str);
        }
        return buf.toString();
    }
}
